package com.production.CoursePlatform.controller;

import com.production.CoursePlatform.entity.Attachment;
import com.production.CoursePlatform.service.AttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

@RestController
@RequestMapping("/attachment")
public class AttachmentController {
    // 此接口已检验
    @Autowired
    private AttachmentService attachmentService;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file,
            @RequestParam("uploadID") int uploadID) {
        if (file.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("文件为空");
        }

        try {
            // 确保上传目录存在
            String uploadDir = "uploads/";
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 保存文件到指定路径
            String fileName = file.getOriginalFilename();
            Path filePath = Paths.get(uploadDir + fileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 获取文件信息并保存到数据库
            Attachment attachment = new Attachment();
            attachment.setAName(fileName);
            attachment.setAPath(filePath.toString());
            attachment.setASize(BigInteger.valueOf(file.getSize()));
            attachment.setUploadID(uploadID);
            attachment.setAType(Files.probeContentType(filePath));

            // 保存到数据库并获取自增ID
            attachment = attachmentService.saveAttachment(attachment);

            // 返回包含新生成的 aID 的响应
            return ResponseEntity.ok(String.valueOf(attachment.getAID()));
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败：" + e.getMessage());
        }
    }

    @GetMapping("/get/{aID}")
    public ResponseEntity<Attachment> getAttachment(@PathVariable int aID) {
        Attachment attachment = attachmentService.getAttachmentById(aID);
        if (attachment == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
        return ResponseEntity.ok(attachment);
    }

    // 文件下载接口
    @GetMapping("/download/{aID}")
    public ResponseEntity<Resource> downloadAttachment(@PathVariable int aID) {
        // 根据 aID 查询文件信息
        Attachment attachment = attachmentService.getAttachmentById(aID);
        if (attachment == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }

        Path filePath = Paths.get(attachment.getAPath()).toAbsolutePath().normalize();
        Resource resource;

        try {
            // 加载文件资源
            resource = new UrlResource(filePath.toUri());
            if (!resource.exists()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
        } catch (MalformedURLException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }

        // 设置响应头以支持文件下载
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(attachment.getAType()))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + attachment.getAName() + "\"")
                .body(resource);
    }
}
